package com.mojo.concurrent.customerproducer;

/**
 * 消费者
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class Customer implements Runnable {
    final Resource resource;

    public Customer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        for (;;) {
            synchronized (resource) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //判断有无资源
                if (!resource.hasResource) {
                    System.out.println("---没有，等待生产---");
                    try {
                        resource.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    //资源消费完毕
                    resource.hasResource = false;
                    //等待资源生成
                    System.out.println(Thread.currentThread().getName() + "customer>>>消费完毕");
                    resource.notify();
                }
                System.out.println("=============================================");
            }
        }
    }
}
